const app = getApp();
const db = wx.cloud.database();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    fileIDs: [],
    show: false,

    message: ''
  },

  //新闻选择
  onChangexinwen(event) {

    this.setData({
      xinwentype: event.detail.value,
      xinwenpd: false,
      show: false
    });
  },
  
  neirong(e) {
    this.setData({
      neirong: e.detail
    })
  },



  oncancelxinwen() {
    this.setData({
      xinwenpd: false,
      show: false
    })
  },




  chosexinwen() {
    this.setData({
      xinwenpd: true,
      show: true
    })
  },

  
  onLoad(option) {
    console.log(option)
    this.setData({})
  },
  onChangea(event) {
    this.setData({
      title: event.detail
    })
  },




  // 选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 9, //默认9,我们这里最多选择8张
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log("选择图片成功", res)
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    })
  },
  //删除图片
  DeleteImg(e) {
    console.log("e", e.currentTarget.dataset.index)
    this.data.imgList.splice(e.currentTarget.dataset.index, 1);
    this.setData({
      imgList: this.data.imgList
    })
  },
  //上传数据
  publish() {
    const title = this.data.title
    const xinwentype = this.data.xinwentype
    const neirong = this.data.neirong
    let d = new Date()
    if (!title) {
      wx.showToast({
        title: '请输入新闻标题',
        icon: 'none'
      })
    } else if (!neirong) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
    } else

    {
      /*文本内容安全检测 */
      const Promise_arr = [];
      Promise.all(Promise_arr).then(res => {
        wx.showLoading({
          title: '发布中....',
        })
        const promiseArr = []
        //只能一张张上传 遍历临时的图片数组
        for (let i = 0; i < this.data.imgList.length; i++) {
          let filePath = this.data.imgList[i]
          let suffix = /\.[^\.]+$/.exec(filePath)[0]; // 正则表达式，获取文件扩展名
          //在每次上传的时候，就往promiseArr里存一个promise，只有当所有的都返回结果时，才可以继续往下执行
          promiseArr.push(new Promise((reslove, reject) => {
            wx.cloud.uploadFile({
              cloudPath: 'myimages/' + new Date().getTime() + suffix,
              filePath: filePath, // 文件路径
            }).then(res => {
              // get resource ID
              console.log("上传结果", res.fileID)
              this.setData({
                fileIDs: this.data.fileIDs.concat(res.fileID)
              })
              reslove()
            }).catch(error => {
              console.log("上传失败", error)
            })
          }))
        }
        //保证所有图片都上传成功
        Promise.all(promiseArr).then(res => {
          var d = new Date(); {
            db.collection('news').add({
              data: {
                zhanghao:wx.getStorageSync('user').zhanghao,
                mima:wx.getStorageSync('user').mima,
                neirong,
                xinwentype,
                title,
                fileIDs: this.data.fileIDs,
                createtime: d.getFullYear() + ' ' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds(),
                time_order: new Date().getTime(),
                pinglun: [],
                dz_openid:[],
                sc_openid:[],
              },
              success: res => {
                wx.hideLoading()
                if (res._id) {

                  wx.showToast({
                    title: '发布成功',
                  })
                  console.log('发布成功', res)
                  wx.navigateBack({
                    delta: 1,
                  })

                }
              },
              fail: err => {
                wx.hideLoading()
                wx.showToast({
                  icon: 'none',
                  title: '网络不给力....'
                })
                console.error('发布失败', err)
              }
            })
          }
        })
      }).catch(res => {

      })
    }




  }
})